//
//  MyViewController.m
//  MemberProject
//
//  Created by MAC OS X on 15/4/2.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "MyViewController.h"
#import "UserDetailInfoViewController.h"
#import "VolunteerRecordViewController.h"
#import "ANScoreViewController.h"
#import "SetingViewController.h"
#import "AddressListViewController.h"
#import "ModelUser.h"
#import "UserInfoManager.h"
#import "UIImageView+WebCache.h"
#import "StarViewController.h"
#import "ZBarCardViewController.h"
#import "AdScrollView.h"
#import "MyViewCollectionViewCell.h"
#import "NewsInfoViewController.h"
#import "MeWebViewController.h"
#import "VolunteerInfoViewController.h"
#import "GroupInfoViewController.h"
#import "ActivityInfoViewController.h"
#import "ClaimPicViewController.h"
#import "ClaimPerInfoViewController.h"
#import "ClaimSuccessViewController.h"
#import "VolunteerClaimViewController.h"
#import "UserInsuranceManager.h"
#import "MJRefreshHeaderView.h"
@interface MyViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,AdScrollViewDelegate,MJRefreshBaseViewDelegate>
@property(strong,nonatomic)UIView *headView;
@property (strong, nonatomic)UIImageView *logoImageView;
@property(strong,nonatomic)UILabel *nameLabel;
@property (strong, nonatomic)UILabel *telLabel;
@property (strong, nonatomic)UILabel *serverTimeLabel;
@property(strong,nonatomic)UILabel *serverScoreLabel;
@property (strong, nonatomic)UITableView *tableView;
@property(strong,nonatomic)NSArray *starArr;
@property(strong,nonatomic)UILabel *starNameLabel;
@property(strong,nonatomic)UIButton *scoreButton;
@property(strong,nonatomic)UILabel *statusLabel;
@property(strong,nonatomic)UIImageView *statusImageView;

@property (strong, nonatomic)UIButton *exitButton;

@property(strong,nonatomic)NSArray *data;


@property(strong,nonatomic)AdScrollView *adScrollView;
@property(strong,nonatomic)UICollectionView *collectionView;

@property(assign,nonatomic)BOOL isFirst;

@property(strong,nonatomic)NSString *netAdState;

@property(strong,nonatomic)UIImageView *politicsStatusImageView;
@property(strong,nonatomic)UIImageView *isVolunteerImageView;

@property(strong,nonatomic)MJRefreshHeaderView *mjRefreshHeaderView;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    UIButton *refreshButton=[UIButton buttonWithType:UIButtonTypeCustom];
//    refreshButton.frame=CGRectMake(0, 0, 25, 25);
//    [refreshButton setImage:[UIImage imageNamed:@"new_refresh"] forState:UIControlStateNormal];
//    [refreshButton addTarget:self action:@selector(chickRefreshButton:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *rightBarButton=[[UIBarButtonItem alloc]initWithCustomView:refreshButton];
//    self.navigationItem.rightBarButtonItem=rightBarButton;
    UIView *collectionViewHeaderView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    collectionViewHeaderView.backgroundColor=[UIColor whiteColor];
    self.netAdState=@"0";
    //监听登陆用户信息刷新的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notificationLoginChangeInfo:) name:NotificationLoginChangeInfo object:nil];
    
    
    
    
//    NSLog(@"current = %@",[self getCurrentVC]);
        self.title=@"我";
    self.automaticallyAdjustsScrollViewInsets=NO;
    AdScrollView *adScrollView=[[AdScrollView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH,SCREEN_WIDTH*3/10)];
        adScrollView.data=@[@{@"image":@"guanggao_4.jpg"},@{@"image":@"guanggao_0.jpg"},@{@"image":@"guanggao_1.jpg"},@{@"image":@"guanggao_2.jpg"},@{@"image":@"guanggao_3.jpg"},@{@"image":@"guanggao_4.jpg"},@{@"image":@"guanggao_0.jpg"}];
    adScrollView.delegate=self;
    [collectionViewHeaderView addSubview:adScrollView];
    self.adScrollView=adScrollView;
    
    UIView *headView=[[UIView alloc]initWithFrame:CGRectMake(0, adScrollView.height+adScrollView.y, SCREEN_WIDTH, 60*SCREEN_WIDTH/320)];
    [collectionViewHeaderView addSubview:headView];
    headView.backgroundColor=[UIColor whiteColor];
    
    UIView *headView1=[[UIView alloc]initWithFrame:CGRectMake(0, 0, headView.width/3, headView.height)];
    [headView addSubview:headView1];
    UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=headView1.bounds;
    [headView1 addSubview:button];
    [button addTarget:self action:@selector(chickDetailButton:) forControlEvents:UIControlEventTouchUpInside];
    self.nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(9, 5, headView1.width/5, (headView1.height-5*2)/2)];
    self.nameLabel.textColor=[UIColor colorWithRed:81/255.0 green:82/255.0 blue:83/255.0 alpha:1];
    self.nameLabel.font=[UIFont systemFontOfSize:15.0f*SCREEN_WIDTH/320];
    self.nameLabel.text=@"*";
    [headView1 addSubview:self.nameLabel];
    
    float height=12*SCREEN_WIDTH/320;
    float width=38*SCREEN_WIDTH/320;
    self.politicsStatusImageView=[[UIImageView alloc]initWithFrame:CGRectMake(self.nameLabel.x+self.nameLabel.width+5, 0, height, height)];
//    self.politicsStatusImageView.backgroundColor=[UIColor redColor];
    [headView1 addSubview:self.politicsStatusImageView];
    self.politicsStatusImageView.image=[UIImage imageNamed:@"groupState"];
    self.politicsStatusImageView.center=CGPointMake(self.politicsStatusImageView.center.x, self.nameLabel.center.y);
    
    
    UIImage *image=[UIImage imageNamed:@"volunteerState"];
    self.isVolunteerImageView=[[UIImageView alloc]initWithFrame:CGRectMake(self.politicsStatusImageView.x+self.politicsStatusImageView.width+5, 0, height*image.size.width/image.size.height, height)];
    self.isVolunteerImageView.image=image;
//    self.isVolunteerImageView.backgroundColor=[UIColor redColor];
    [headView1 addSubview:self.isVolunteerImageView];
    self.isVolunteerImageView.center=CGPointMake(self.isVolunteerImageView.center.x, self.nameLabel.center.y);
    
    
    self.statusImageView=[[UIImageView alloc]initWithFrame:CGRectMake(headView1.width-width-3, self.nameLabel.y, width, height)];
    self.statusImageView.image=[UIImage imageNamed:@"v"];
    self.statusImageView.center=CGPointMake(self.statusImageView.center.x, self.nameLabel.center.y);
    [headView1 addSubview:self.statusImageView];
    
    self.telLabel=[[UILabel alloc]initWithFrame:CGRectMake(self.nameLabel.x, self.nameLabel.y+self.nameLabel.height, headView1.width-2*9, self.nameLabel.height)];
    [headView1 addSubview:self.telLabel];
    self.telLabel.text=@"13800130000";
    self.telLabel.textColor=[UIColor colorWithRed:81/255.0 green:82/255.0 blue:83/255.0 alpha:1];
    self.telLabel.font=[UIFont systemFontOfSize:14.0f*SCREEN_WIDTH/320];
    UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(headView1.width-1, 5, 1, headView1.height-5*2)];
    lineView.backgroundColor=[UIColor colorWithRed:247/255.0 green:248/255.0 blue:249/255.0 alpha:1];
    [headView1 addSubview:lineView];
    
    UIView *headView2=[[UIView alloc]initWithFrame:CGRectMake(headView1.width+headView1.x, 0, headView.width/3*2/3, headView.height)];
    [headView addSubview:headView2];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 5, headView2.width, (headView2.height-5*2)/2)];
    label.text=@"服务星级";
    label.textColor=[UIColor colorWithRed:81/255.0 green:82/255.0 blue:83/255.0 alpha:1];
    label.font=[UIFont systemFontOfSize:15.0f*SCREEN_WIDTH/320];
    label.textAlignment=NSTextAlignmentCenter;
    [headView2 addSubview:label];
    
    float starWidth=13*SCREEN_WIDTH/320;
    NSMutableArray *arrM=[NSMutableArray array];
    for(int i=0;i<5;i++){
        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        button.frame=CGRectMake((headView2.width-5*starWidth)/2+i*starWidth, label.y+label.height+(label.height-starWidth)/2, starWidth, starWidth);
        [headView2 addSubview:button];
        [arrM addObject:button];
    }
    self.starArr=arrM;
    
    lineView=[[UIView alloc]initWithFrame:CGRectMake(headView2.width-1, 5, 1, headView1.height-5*2)];
    lineView.backgroundColor=[UIColor colorWithRed:247/255.0 green:248/255.0 blue:249/255.0 alpha:1];
    [headView2 addSubview:lineView];
    
    
    
    UIView *headView3=[[UIView alloc]initWithFrame:CGRectMake(headView2.width+headView2.x, 0, headView.width/3*2/3, headView.height)];
    [headView addSubview:headView3];
    label=[[UILabel alloc]initWithFrame:CGRectMake(0, 5, headView3.width, (headView3.height-5*2)/2)];
    label.font=[UIFont systemFontOfSize:15.0f*SCREEN_WIDTH/320];
    NSMutableAttributedString *attriStr=[[NSMutableAttributedString alloc]initWithString:@"时长(h)"];
    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:81/255.0 green:82/255.0 blue:83/255.0 alpha:1] range:NSMakeRange(0, 2)];
    [attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:197/255.0 green:199/255.0 blue:200/255.0 alpha:1] range:NSMakeRange(2, 3)];
    label.attributedText=attriStr;
//    label.text=@"时长";
//    label.textColor=[UIColor colorWithRed:81/255.0 green:82/255.0 blue:83/255.0 alpha:1];
    label.textAlignment=NSTextAlignmentCenter;
    [headView3 addSubview:label];
    
    self.serverTimeLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, label.y+label.height, headView3.width, label.height)];
    self.serverTimeLabel.textAlignment=NSTextAlignmentCenter;
    self.serverTimeLabel.textColor=[UIColor colorWithRed:77/255.0 green:208/255.0 blue:200/255.0 alpha:1];
    self.serverTimeLabel.text=@"10";
    self.serverTimeLabel.font=[UIFont systemFontOfSize:14.0f*SCREEN_WIDTH/320];
    [headView3 addSubview:self.serverTimeLabel];
    lineView=[[UIView alloc]initWithFrame:CGRectMake(headView2.width-1, 5, 1, headView1.height-5*2)];
    lineView.backgroundColor=[UIColor colorWithRed:247/255.0 green:248/255.0 blue:249/255.0 alpha:1];
    [headView3 addSubview:lineView];
    
    
    UIView *headView4=[[UIView alloc]initWithFrame:CGRectMake(headView3.width+headView3.x, 0, headView.width/3*2/3, headView.height)];
    [headView addSubview:headView4];
    label=[[UILabel alloc]initWithFrame:CGRectMake(0, 5, headView4.width, (headView4.height-5*2)/2)];
    label.font=[UIFont systemFontOfSize:15.0f*SCREEN_WIDTH/320];
    label.text=@"积分";
    label.textColor=[UIColor colorWithRed:81/255.0 green:82/255.0 blue:83/255.0 alpha:1];
    label.textAlignment=NSTextAlignmentCenter;
    [headView4 addSubview:label];
    self.serverScoreLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, label.y+label.height, headView4.width, label.height)];
    self.serverScoreLabel.textAlignment=NSTextAlignmentCenter;
    self.serverScoreLabel.textColor=[UIColor colorWithRed:249/255.0 green:63/255.0 blue:0/255.0 alpha:1];
    self.serverScoreLabel.text=@"10";
    self.serverScoreLabel.font=[UIFont systemFontOfSize:14.0f*SCREEN_WIDTH/320];
    [headView4 addSubview:self.serverScoreLabel];
    
    collectionViewHeaderView.height=self.adScrollView.height+headView.height;
    
    
    UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection=UICollectionViewScrollDirectionVertical;
    layout.minimumInteritemSpacing=1;
    layout.minimumLineSpacing=1;
    layout.itemSize=CGSizeMake((SCREEN_WIDTH-2*1)/3,85*SCREEN_WIDTH/320);
    layout.sectionInset=UIEdgeInsetsMake(1, 0,1, 0);
    layout.headerReferenceSize=CGSizeMake(SCREEN_WIDTH, collectionViewHeaderView.height);
//    height=SCREEN_HEIGHT-64-49-headView.height-self.adScrollView.height;
    
    self.data=@[@{@"name":@"志愿记录",@"image":[UIImage imageNamed:@"record_icon96"]},@{@"name":@"服务积分",@"image":[UIImage imageNamed:@"integral_icon96"]},@{@"name":@"二维码名片",@"image":[UIImage imageNamed:@"card_icon96"]},@{@"name":@"扫一扫",@"image":[UIImage imageNamed:@"scan_icon96"]},@{@"name":@"通讯录",@"image":[UIImage imageNamed:@"address-list_icon96"]},@{@"name":@"设置",@"image":[UIImage imageNamed:@"setup_icon96"]}];
    float lineCount=self.data.count/3;
    if(self.data.count%3!=0){
        lineCount++;
    }
    height=lineCount*(85*SCREEN_WIDTH/320)+3*1;
    UICollectionView *collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH,SCREEN_HEIGHT-64-49) collectionViewLayout:layout];
    collectionView.alwaysBounceVertical=YES;
    [collectionView addSubview:collectionViewHeaderView];
    collectionView.dataSource=self;
    collectionView.delegate=self;
    [self.view addSubview:collectionView];
    collectionView.backgroundColor=[UIColor colorWithRed:219/255.0 green:220/255.0 blue:221/255.0 alpha:1];
//    collectionView.backgroundColor=[UIColor whiteColor];
    self.collectionView=collectionView;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    self.mjRefreshHeaderView=header;
    header.delegate=self;
    header.scrollView = self.collectionView;
    
    
    [collectionView registerNib:[UINib nibWithNibName:@"MyViewCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"CellIdentifier"];
    [self refreshData];
    
    UIView *collectionViewFooterView=[[UIView alloc]initWithFrame:CGRectMake(0, collectionViewHeaderView.height+85*SCREEN_WIDTH/320*2+1*3, SCREEN_WIDTH, collectionView.height-(collectionViewHeaderView.height+85*SCREEN_WIDTH/320*2+1*3)+300)];
    collectionViewFooterView.backgroundColor=[UIColor colorWithRed:244/255.0 green:245/255.0 blue:246/255.0 alpha:1];
    [collectionView addSubview:collectionViewFooterView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(userPositionDidChange:) name:NotificationUserPositionDidChange object:nil];
    self.isFirst=YES;
    [self netLoadAd];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.isFirst==NO){
        [self loadAd];
    }
    self.isFirst=NO;
}

-(void)chickRefreshButton:(UIButton *)sender{
    //刷新
    
    NSString *telStr = [UserInfoManager sharedManager].modelMser.loginMobile;
    ;
   NSString *tel=  [[BuaatVolunteerServerSDK sharedInstance]encryptStrWithPublicKey:[[BuaatVolunteerServerSDK sharedInstance]decryptStrWithPublicKey:telStr]];
    
    NSString *loginPd = [UserInfoManager sharedManager].modelMser.loginPassword;
    sender.userInteractionEnabled=NO;
    [SVProgressHUD showWithStatus:@"刷新中" maskType:SVProgressHUDMaskTypeClear];
    [[BuaatVolunteerServerSDK sharedInstance]requestAuthVolunteerWithVolunteerMobile:tel volunteerPwd:loginPd success:^(NSHTTPURLResponse *response, id responseObject) {
        //密码正确
        sender.userInteractionEnabled=YES;
        [SVProgressHUD dismiss];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            id resultDic = responseObject[@"result"];
            if ([resultDic isKindOfClass:[NSDictionary class]]) {
                NSMutableDictionary *changeDic = [[NSMutableDictionary alloc]initWithDictionary:resultDic];
                [changeDic setValue:loginPd forKey:@"loginPassword"];
                
//                [SVProgressHUD dismiss];
                ModelUser *user = [ModelUser getUserForDic:changeDic];
                [UserInfoManager sharedManager].modelMser = user;
                
                
                [[UserInfoManager sharedManager]writeLocalLog:changeDic];
                
                [self refreshData];

                
            }
            
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        sender.userInteractionEnabled=YES;
    }];
    
    
    
    [[UserInsuranceManager sharedManager]setupUserInsurance:^{
        
    }];
    
    

}

//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(void)userPositionDidChange:(NSNotification *)sender{
    [self netLoadAd];
}

-(void)notificationLoginChangeInfo:(NSNotification *)sender{
    [self refreshData];
}

//更新数据
-(void)refreshData{
    ModelUser *modeluser = [UserInfoManager sharedManager].modelMser;
//    //头像
//    [self.logoImageView sd_setImageWithURL:[NSURL URLWithString:modeluser.headImageUrl] placeholderImage:nil];
    if(modeluser.userName.length!=0){
        self.nameLabel.text=[NSString stringWithFormat:@"*%@",[modeluser.userName substringWithRange:NSMakeRange(modeluser.userName.length-1, 1)]];
    }
    //手机号码
    NSString *text;
    if(modeluser.loginMobile.length==0){
        text=@"";
    }else{
        text=[[BuaatVolunteerServerSDK sharedInstance]decryptStrWithPublicKey:modeluser.loginMobile];
    }
    self.telLabel.text =[NSString stringWithFormat:@"%@",text];
    //认证
//    modeluser.userStatus=@"2";
//    modeluser.politicalStatus=@"0";
    if([modeluser.userStatus intValue]==0){
        //验证成功
//        self.statusImageView.image=[UIImage imageNamed:@"yrz"];
        self.statusImageView.hidden=YES;
        self.politicsStatusImageView.hidden=NO;
        self.isVolunteerImageView.hidden=NO;
        
        self.politicsStatusImageView.x=SCREEN_WIDTH/3-2*5-self.isVolunteerImageView.width-self.politicsStatusImageView.width;
        
        self.isVolunteerImageView.x=SCREEN_WIDTH/3-5-self.isVolunteerImageView.width;
        

        int politicalStatus=[modeluser.politicalStatus intValue];
        if(politicalStatus==0){
            self.politicsStatusImageView.image=[UIImage imageNamed:@"groupState"];
        }else if (politicalStatus==1||politicalStatus==2||politicalStatus==4){
            self.politicsStatusImageView.image=[UIImage imageNamed:@"orgState"];
        }else{
            self.politicsStatusImageView.hidden=YES;
        }
    }else if ([modeluser.userStatus intValue]==2){
        //验证不通过
        self.statusImageView.image=[UIImage imageNamed:@"wrz"];
        self.statusImageView.hidden=NO;
        self.politicsStatusImageView.hidden=NO;
        self.isVolunteerImageView.hidden=NO;
        
        int offsetX=((self.statusImageView.x-self.nameLabel.width-self.nameLabel.x)-self.isVolunteerImageView.width-self.politicsStatusImageView.width)/3;
        self.politicsStatusImageView.x=self.nameLabel.width+self.nameLabel.x+offsetX;
        self.isVolunteerImageView.x=self.politicsStatusImageView.width+self.politicsStatusImageView.x+offsetX;
        
        int politicalStatus=[modeluser.politicalStatus intValue];
        if(politicalStatus==0){
            self.politicsStatusImageView.image=[UIImage imageNamed:@"groupState"];
        }else if (politicalStatus==1||politicalStatus==2||politicalStatus==4){
            self.politicsStatusImageView.image=[UIImage imageNamed:@"orgState"];
        }else{
            self.politicsStatusImageView.hidden=YES;
        }
        
    }else{
        
        self.statusImageView.image=[UIImage imageNamed:@"rzz"];
        self.statusImageView.hidden=NO;
        self.politicsStatusImageView.hidden=NO;
        self.isVolunteerImageView.hidden=NO;
        
        int offsetX=((self.statusImageView.x-self.nameLabel.width-self.nameLabel.x)-self.isVolunteerImageView.width-self.politicsStatusImageView.width)/3;
        self.politicsStatusImageView.x=self.nameLabel.width+self.nameLabel.x+offsetX;
        self.isVolunteerImageView.x=self.politicsStatusImageView.width+self.politicsStatusImageView.x+offsetX;
        
        int politicalStatus=[modeluser.politicalStatus intValue];
        if(politicalStatus==0){
            self.politicsStatusImageView.image=[UIImage imageNamed:@"groupState"];
        }else if (politicalStatus==1||politicalStatus==2||politicalStatus==4){
            self.politicsStatusImageView.image=[UIImage imageNamed:@"orgState"];
        }else{
            self.politicsStatusImageView.hidden=YES;
        }
        
    }
//    if([modeluser.status intValue]==0){
//        self.statusLabel.hidden=YES;
//        self.statusImageView.hidden=NO;
//    }else{
//        self.statusLabel.hidden=NO;
//        self.statusImageView.hidden=YES;
//    }
    //服务时长
    self.serverTimeLabel.text =[NSString stringWithFormat:@"%d",[modeluser.volunteerServiceHours intValue]];
    //星级
    [self starNumWithNum:[modeluser.volunteerLevel intValue]];
//    //A/N星级志愿
//    self.starNameLabel.text =[NSString stringWithFormat:@"%d星级志愿者",[modeluser.voluteerLevel intValue]];
    //积分
    NSString *tempStr=[NSString stringWithFormat:@"%d",[modeluser.volunteerScore intValue]];
    self.serverScoreLabel.text=tempStr;
}

-(void)starNumWithNum:(int)num{
    if(self.starArr==nil){
        
    }else{
        for (int i =0; i<self.starArr.count; i++) {
            //
            UIButton *starBtn=self.starArr[i];
            if (i<num) {
                [starBtn setImage:[UIImage imageNamed:@"star3_icon26.png"] forState:UIControlStateNormal];
            }else{
                [starBtn setImage:[UIImage imageNamed:@"star1_icon26.png"] forState:UIControlStateNormal];
            }
        }
    }
}

- (void)chickExitButton:(UIButton *)sender {
    //退出
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - collectionView delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.data.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"CellIdentifier";
    MyViewCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.textLabel.text=self.data[indexPath.row][@"name"];
    cell.imageView.image=self.data[indexPath.row][@"image"];
    return cell;
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//    if(indexPath.row==1){
//        return CGSizeMake((collectionView.width-1)/3, (collectionView.width-1)/3);
//    }else{
//        return <#expression#>
//    }
//}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:{
            //志愿记录
            VolunteerRecordViewController *vc=[[VolunteerRecordViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
//            NewsInfoViewController *newInfoVC = [[NewsInfoViewController alloc]initWithNibName:@"NewsInfoViewController" bundle:nil];
//            [self.navigationController pushViewController:newInfoVC animated:YES];
        }
            break;
        case 1:{
            //服务积分
            ANScoreViewController *vc=[[ANScoreViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:{
            //二维码名片
//            ClaimPicViewController *zbarCardVC=[[ClaimPicViewController alloc]init];
            
            ZBarCardViewController *zbarCardVC = [[ZBarCardViewController alloc]initWithNibName:@"ZBarCardViewController" bundle:nil];
            [self.navigationController pushViewController:zbarCardVC animated:YES];
        }
            break;
        case 3:{
            //扫一扫
            [self showQz:MyZbarStyle];
            [self getZBarPushBlockStrFromMyView:^(id result) {
                [self handleCode:result];

//                if ([result hasPrefix:@"VOLUTEER"]) {
//                    [SVProgressHUD showInfoWithStatus:result maskType:SVProgressHUDMaskTypeBlack];
//                }else
//                {
//                    
//                }
                
            }];
        }
            break;
        case 4:{
            //通讯录
            AddressListViewController *vc=[[AddressListViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 5:{
            //设置
            SetingViewController *vc=[[SetingViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }


}
#pragma mark - tableView
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(SCREEN_HEIGHT>480){
        return (SCREEN_HEIGHT-64-49-5*5-self.headView.height-self.adScrollView.height-40)/6;
    }else{
        return (SCREEN_HEIGHT-20)/15;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:{
            //志愿记录
            VolunteerRecordViewController *vc=[[VolunteerRecordViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1:{
            //服务积分
            ANScoreViewController *vc=[[ANScoreViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2:{
            //二维码名片
            ZBarCardViewController *zbarCardVC = [[ZBarCardViewController alloc]initWithNibName:@"ZBarCardViewController" bundle:nil];
            [self.navigationController pushViewController:zbarCardVC animated:YES];
        }
            break;
        case 3:{
            //扫一扫
//            [self showQz:MyZbarStyle];
//            [self getZBarPushBlockStr:^(id result) {
//                if ([result hasPrefix:@"VOLUTEER"]) {
//                    [SVProgressHUD showInfoWithStatus:result maskType:SVProgressHUDMaskTypeBlack];
//                }else
//                {
//                    
//                }
//                
//            }];
            [self handleCode:@"V:"];
        }
            break;
        case 4:{
            //通讯录
            AddressListViewController *vc=[[AddressListViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 5:{
            //设置
            SetingViewController *vc=[[SetingViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"CellIdentifier";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text=self.data[indexPath.row];
    if(SCREEN_HEIGHT>568){
        cell.textLabel.font=[UIFont systemFontOfSize:19.0f];
    }else{
        cell.textLabel.font=[UIFont systemFontOfSize:15.0f];
    }
    return cell;
}

#pragma mark - headView
-(void)chickDetailButton:(UIButton *)sender{
    //详细
    UserDetailInfoViewController *vc=[[UserDetailInfoViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)chickQuestionButton:(UIButton *)sender{
    //按动问号
    ANScoreViewController *vc=[[ANScoreViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)chickScoreButton:(UIButton *)sender{
    //积分按钮
    ANScoreViewController *vc=[[ANScoreViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)chickStarButton:(UIButton *)sender{
    //按动星星
//    StarViewController *vc=[[StarViewController alloc]init];
//    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - AdScrollView
-(void)adScrollView:(AdScrollView *)adScrollView tapImageViewWithIndex:(NSInteger)index urlStr:(NSString *)urlStr{
    MeWebViewController *vc=[[MeWebViewController alloc]init];
    vc.urlStr=urlStr;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 广告
-(void)loadAd{
    NSString *appRefreshAdDateStr=[[NSUserDefaults standardUserDefaults]valueForKey:KAppRefreshDateStr_Me];
    NSDateFormatter *f=[[NSDateFormatter alloc]init];
    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *appRefreshAdDate=[f dateFromString:appRefreshAdDateStr];
    if(![Utils isCurrentDay:appRefreshAdDate]||appRefreshAdDateStr.length==0){
        //刷新
        [self netLoadAd];
        
    }else{
        //不刷新
    }
}

-(void)netLoadAd{
    ModelUser *modeluser = [UserInfoManager sharedManager].modelMser;
    NSString *tempState=[NSString stringWithFormat:@"%d",[self.netAdState intValue]+1];
    self.netAdState=[NSString stringWithFormat:@"%@",tempState];
    __weak MyViewController *this=self;
    [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:KAppRefreshDateStr_Me];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[BuaatVolunteerServerSDK sharedInstance]requestAdvertEnquiryWithVolunteerCode:modeluser.volunteerCode module:@"me" location:[[NSUserDefaults standardUserDefaults]valueForKey:KUserPosition] success:^(NSHTTPURLResponse *response, id responseObject) {
        if(this){
            if([this.netAdState isEqualToString:tempState]){
                NSArray *resultArr=responseObject[@"result"];
                if([resultArr isKindOfClass:[NSArray class]]){
                    if(resultArr.count!=0){
                        [resultArr sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]]];
                        NSMutableArray *arrM=[NSMutableArray array];
                        NSDictionary *d=[resultArr lastObject];
                        [arrM addObject:@{@"image":d[@"adImg"],@"link":d[@"adLink"]}];
                        for(int i=0;i<resultArr.count;i++){
                            NSDictionary *dic=resultArr[i];
                            [arrM addObject:@{@"image":dic[@"adImg"],@"link":dic[@"adLink"]}];
                        }
                        d=resultArr[0];
                        [arrM addObject:@{@"image":d[@"adImg"],@"link":d[@"adLink"]}];
                        this.adScrollView.data=arrM;
                    }
                    
                    NSDateFormatter *f=[[NSDateFormatter alloc]init];
                    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSString *dateStr=[f stringFromDate:[NSDate date]];
                    [[NSUserDefaults standardUserDefaults]setObject:dateStr forKey:KAppRefreshDateStr_Me];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }else{
                    [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:KAppRefreshDateStr_Me];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
                
                
            }
        }
    } failure:^(NSHTTPURLResponse *response, NSError *error) {
        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:KAppRefreshDateStr_Me];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
    
}

#pragma mark - qcord
-(void)handleCode:(NSString *)code{
    if([code hasPrefix:@"V:"]||[code hasPrefix:@"v:"]){
        //志愿者
        NSString *volunteerCode=[code substringFromIndex:2];
        [SVProgressHUD show];
        [[BuaatVolunteerServerSDK sharedInstance]requestQrcodeVolunteerInfoWithVolunteerCode:volunteerCode success:^(NSHTTPURLResponse *response, id responseObject) {
            NSDictionary *resultDic=responseObject[@"result"];
            if([resultDic isKindOfClass:[NSDictionary class]]){
                [SVProgressHUD dismiss];
                VolunteerInfoViewController *vc=[[VolunteerInfoViewController alloc]init];
                vc.resultDic=resultDic;
                vc.volunteerCode=volunteerCode;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [SVProgressHUD showErrorWithStatus:@"没有该自愿者信息"];
            }
            
        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];
    }else if([code hasPrefix:@"G:"]||[code hasPrefix:@"g:"]){
        //组织
        NSString *groupCode=[code substringFromIndex:2];
        [SVProgressHUD show];
        [[BuaatVolunteerServerSDK sharedInstance]requestQrcodeGroupInfoWithGroupCode:groupCode success:^(NSHTTPURLResponse *response, id responseObject) {
            NSDictionary *resultDic=responseObject[@"result"];
            if([resultDic isKindOfClass:[NSDictionary class]]){
                [SVProgressHUD dismiss];
                GroupInfoViewController *vc=[[GroupInfoViewController alloc]init];
                vc.groupCode=groupCode;
                vc.resultDic=resultDic;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [SVProgressHUD showErrorWithStatus:@"没有该团体信息"];
            }
        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];
    }else if ([code hasPrefix:@"A:"]||[code hasPrefix:@"a:"]){
        //活动
        [SVProgressHUD show];
        NSString *activityCode=[code substringFromIndex:2];
        [[BuaatVolunteerServerSDK sharedInstance]requestQrcodeActivityInfoWithActivityCode:activityCode success:^(NSHTTPURLResponse *response, id responseObject) {
            NSDictionary *resultDic=responseObject[@"result"];
            if([resultDic isKindOfClass:[NSDictionary class]]){
                [SVProgressHUD dismiss];
                ActivityInfoViewController *vc=[[ActivityInfoViewController alloc]init];
                vc.activityCode=activityCode;
                vc.resultDic=resultDic;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [SVProgressHUD showErrorWithStatus:@"没有该活动信息"];
            }
        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];
    }else{
        //组织
        NSString *groupCode=code;
        [SVProgressHUD show];
        [[BuaatVolunteerServerSDK sharedInstance]requestQrcodeGroupInfoWithGroupCode:groupCode success:^(NSHTTPURLResponse *response, id responseObject) {
            NSDictionary *resultDic=responseObject[@"result"];
            NSString *msg = responseObject[@"msg"];
            if([resultDic isKindOfClass:[NSDictionary class]]){
                [SVProgressHUD dismiss];
                GroupInfoViewController *vc=[[GroupInfoViewController alloc]init];
                vc.groupCode=groupCode;
                vc.resultDic=resultDic;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [SVProgressHUD showErrorWithStatus:@"没有该社团信息"];
            }
        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];

    }
}

#pragma mark - MJRefreshBaseView delegate
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView{
    if(refreshView.isRefreshing==NO){
        NSString *telStr = [UserInfoManager sharedManager].modelMser.loginMobile;
        ;
        NSString *tel=  [[BuaatVolunteerServerSDK sharedInstance]encryptStrWithPublicKey:[[BuaatVolunteerServerSDK sharedInstance]decryptStrWithPublicKey:telStr]];
        
        NSString *loginPd = [UserInfoManager sharedManager].modelMser.loginPassword;
        [[BuaatVolunteerServerSDK sharedInstance]requestAuthVolunteerWithVolunteerMobile:tel volunteerPwd:loginPd success:^(NSHTTPURLResponse *response, id responseObject) {
            [self.mjRefreshHeaderView endRefreshing];
            //密码正确
            if ([responseObject isKindOfClass:[NSDictionary class]]) {
                id resultDic = responseObject[@"result"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    NSMutableDictionary *changeDic = [[NSMutableDictionary alloc]initWithDictionary:resultDic];
                    [changeDic setValue:loginPd forKey:@"loginPassword"];
                    
                    ModelUser *user = [ModelUser getUserForDic:changeDic];
                    [UserInfoManager sharedManager].modelMser = user;
                    
                    
                    [[UserInfoManager sharedManager]writeLocalLog:changeDic];
                    
                    [self refreshData];
                    
                    
                }
                
            }
        } failure:^(NSHTTPURLResponse *response, NSError *error) {
            [self.mjRefreshHeaderView endRefreshing];
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];
        [[UserInsuranceManager sharedManager]setupUserInsurance:^{
            
        }];

    }
}
@end
